from db.database import db_session as Session
from db.models.llm_profile.llm_model import LLM_MODEL
from db.models.llm_profile import schemas


# 基于id获取模型
def get_llm_model_by_id(llm_model_id: int):
    llm = Session.query(LLM_MODEL).filter(LLM_MODEL.id == llm_model_id).first()
    if llm is None: raise Exception("模型不存在")
    return llm.to_dict()


# 获取所有模型
def get_llm_models(skip: int = 0, limit: int = 100):
    llm = Session.query(LLM_MODEL).offset(skip).limit(limit).all()
    return [llm_.to_dict() for llm_ in llm]


# 创建模型
def create_llm_model(llm_model: schemas.llm_model_create):
    try:
        db_llm_model = LLM_MODEL(**llm_model.to_dict())
        Session.add(db_llm_model)
        Session.commit()
        Session.refresh(db_llm_model)
        return db_llm_model
    except Exception as e:
        print(f"调用出错:{e}")
        return None


# 更新模型
def update_llm_model(llm_model_id: int):
    db_llm_model = get_llm_model_by_id(llm_model_id)
    if not db_llm_model:
        return None
    db_llm_model.name = LLM_MODEL.name
    db_llm_model.description = LLM_MODEL.description
    db_llm_model.base_url = LLM_MODEL.base_url
    db_llm_model.api_key = LLM_MODEL.api_key
    Session.commit()
    Session.refresh(db_llm_model)
    return db_llm_model


# 删除模型
def delete_llm_model(llm_model_id: int):
    db_llm_model = get_llm_model_by_id(llm_model_id)
    if not db_llm_model:
        return None
    Session.delete(db_llm_model)
    Session.commit()
    return db_llm_model
